package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.Admin;
import com.tanhua.model.vo.AdminVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 用户登陆
    public Map<String, Object> login(Map params) {
        // 解析参数
        String username = (String) params.get("username");
        String password = (String) params.get("password");
        String code = (String) params.get("verificationCode");
        String uuid = (String) params.get("uuid");

        // 判断用户名或密码是否为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new BusinessException("用户名或密码不能为空");
        }

        // 判断验证码是否为空
        if (StringUtils.isEmpty(code)) {
            throw new BusinessException("验证码不能为空");
        }

        // 校验验证码
        // 从redis中获取数据
        String redisCode = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (StringUtils.isEmpty(redisCode) || !code.equals(redisCode)) {
            throw new BusinessException("验证码不正确");
        }
        redisTemplate.delete(Constants.CAP_CODE + uuid);

        // 根据用户名查询用户信息
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class)
                .eq(Admin::getUsername, username));
        if (admin == null || !SecureUtil.md5(password).equals(admin.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        // 生成token
        Map<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", username);

        String token = JwtUtils.getToken(map);

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("token", token);
        return retMap;
    }

    // 根据登陆用户的id查询数据
    public AdminVo findById() {

        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class)
                .eq(Admin::getId, AdminHolder.getUserId()));

        return AdminVo.init(admin);

    }
}
